package cn.lzd.hbase.me;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;

/**
 * 学习：先了解、后深入；先记录、后记忆；先理论、后实践；先模仿、后创新
 * Created by lzd on 2018/5/19.
 */
public class CreateTable {

    public static final String TABLE_NAME = "testapi";
    public static final String COLUMNFAMILY_NAME = "cf";
    public static final String ROW_KEY = "rowkey1";

    public static void main(String[] args) throws IOException {

        Configuration config = HBaseConfiguration.create();
        Connection connection = ConnectionFactory.createConnection(config);
        Admin admin = connection.getAdmin();

        Table table = connection.getTable(TableName.valueOf(TABLE_NAME));
        TableName name = table.getName();

        initBeforeCreate(admin, name);
        createTable(admin, table);

        try {
            Put put = new Put(ROW_KEY.getBytes());
            put.addColumn(COLUMNFAMILY_NAME.getBytes(), "age".getBytes(), "25".getBytes());
            put.addColumn(COLUMNFAMILY_NAME.getBytes(), "age".getBytes(), "26".getBytes());
            put.addColumn(COLUMNFAMILY_NAME.getBytes(), "age".getBytes(), "27".getBytes());
            put.addColumn(COLUMNFAMILY_NAME.getBytes(), "age".getBytes(), "28".getBytes());
            table.put(put);
            System.out.println("end ....");
        } finally {
            table.close();
            connection.close();
        }
    }

    private static void createTable(Admin admin, Table table) throws IOException {
        HTableDescriptor desc = new HTableDescriptor(table.getName());
        HColumnDescriptor family = new HColumnDescriptor(COLUMNFAMILY_NAME);
        family.setMaxVersions(3);
        family.setMinVersions(0);
        desc.addFamily(family);
        admin.createTable(desc);
    }

    private static void initBeforeCreate(Admin admin, TableName name) throws IOException {
        if (admin.tableExists(name)) {
            if (admin.isTableEnabled(name)) {
                admin.disableTable(name);
            }
            admin.deleteTable(name);
        }
    }


}
